package Leetcode;

import java.util.Arrays;

/**
 * @ Author     ：侯耀祖
 * @ Description：
 */
public class findKthLargest {
    /**
     * 寻找数组中的第K个最大元素
     * @param nums 输入的整数数组
     * @param k 指定的第K大元素的序号
     * @return 数组中第K大的元素
     */
    public int findKthLargest(int[] nums, int k) {
        int headSize = nums.length;
        buildMaxHeap(nums, headSize);
        for (int i = nums.length - 1; i >= nums.length - k + 1; i--) {
            swap(nums, 0, i);
            --headSize;
            maxHeapify(nums, 0, headSize);
        }
        return nums[0];
    }
    public void buildMaxHeap(int[] a, int heapSize){
        for (int i = heapSize / 2 - 1; i >= 0; i--) {
            maxHeapify(a, i, heapSize);
        }
    }

    private void maxHeapify(int[] a, int i, int heapSize) {
        int l = i * 2 + 1, r = i * 2 + 2, largest = i;
        if (l < heapSize && a[l] > a[largest]){
            largest = l;
        }
        if (r < heapSize && a[r] > a[largest]){
            largest = r;
        }
        if (largest != i){
            swap(a, i, largest);
            maxHeapify(a, largest, heapSize);
        }
    }
    public void swap(int[] arr, int i, int j) {
        int temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
    }
}
